export default class extends think.Controller {
  async __before() {
    // 根据token值获取用户id
    const publicController = this.config("publicController") || [];
    const publicAction = this.config("publicAction") || [];
    // 如果为非公开，则验证用户是否登录
    const controllerAction = this.ctx.controller + "/" + this.ctx.action;

    // 校验白名单
    if (
      !publicController.includes(this.ctx.controller) &&
      !publicAction.includes(controllerAction) &&
      false
    ) {
      this.ctx.state.token = this.ctx.header["authorization"] || "";
      const tokenSerivce = think.service("token", "admin");
      this.ctx.state.userId = await tokenSerivce.getUserId(
        this.ctx.state.token
      );
      if (this.ctx.state.userId <= 0) {
        return this.fail(401, "请先登录");
      }
    } else {
      console.log("未拦截，不需要登录");
    }
  }

  /**
   * 获取时间戳
   * @returns {Number}
   */
  getTime() {
    return parseInt((Date.now() / 1000).toString());
  }
  /**
   * 获取时间戳
   * @returns {Number}
   */
  getDateTime() {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const h = date.getHours();
    const m = date.getMinutes();
    const s = date.getSeconds();
    return `${year}-${month}-${day} ${h}:${m}:${s}`;
  }

  /**
   * 获取当前登录用户的id
   * @returns {*}
   */
  getLoginUserId() {
    return this.ctx.state.userId;
  }
}
